﻿using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbitImproved : MonoBehaviour {

	public Transform targetTransform;
	private Vector3 pesen;

	public float distance = 10.0f;
	private float xSpeed = Screen.width / 8;
	private float ySpeed = Screen.height / 8;
	
	public float yMinLimit = -20f;
	public float yMaxLimit = 80f;
	
	public float distanceMin = .5f;
	public float distanceMax = 20f;

	public float lerpSpeed = 2.5F;

	float x = 0.0f;
	float y = 0.0f;

	Quaternion rotation;
	Vector3 position;

	// Use this for initialization
	void Start () {
		pesen = targetTransform.position;
		rotation = targetTransform.rotation;
		position = targetTransform.position;
		Vector3 angles = transform.eulerAngles;
		x = angles.y;
		y = angles.x;
		
		// Make the rigid body not change rotation
		if (GetComponent<Rigidbody>())
			GetComponent<Rigidbody>().freezeRotation = true;
	}

	void Update()
	{
		pesen = Vector3.Lerp(pesen, targetTransform.position, Time.deltaTime*lerpSpeed);
		updateCamera ();
	}
	
	public void OnScroll()
	{
		distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);
		RaycastHit hit;
		if (Physics.Linecast (pesen, pesen, out hit)) {
			distance -=  hit.distance;
		}
	}

	public void OnDrag()
	{
		x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
		y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
		y = ClampAngle(y, yMinLimit, yMaxLimit);

		rotation = Quaternion.Euler(y, x, 0);
	}

	public void changeTarget(Transform newTargetTransform)
	{
		targetTransform = newTargetTransform;
	}

	void updateCamera()
	{
		Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
		position = rotation * negDistance + pesen;

		transform.rotation = rotation;
		transform.position = position;
	}

	public static float ClampAngle(float angle, float min, float max)
	{
		if (angle < -360F)
			angle += 360F;
		if (angle > 360F)
			angle -= 360F;
		return Mathf.Clamp(angle, min, max);
	}
	
	
}